package com.shire.movienizerdroid;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
import android.widget.Toast;

import com.shire.movienizerdroid.activity.AwesomePagerActivity;
import com.shire.movienizerdroid.activity.MDPreferenceActivity;
import com.shire.movienizerdroid.activity.ViewMovieActivity;
import com.shire.movienizerdroid.db.DataSource;
import com.shire.movienizerdroid.thirdparty.filechooser.FileChooserActivity;
import com.shire.movienizerdroid.view.adapter.MovieListAdapter;

public class MovienizerDroidActivity extends Activity implements AdapterView.OnItemClickListener, FilterQueryProvider, DialogInterface.OnClickListener {
	public static final String LOG_TAG = "MovienizerDroid";

	private static final String DATABASE_FILE_FILTER = ".*\\.dmo$";
	public static final String FILTER_EXTRA = "filter";

	private ListView lvMovies;

	private boolean reloadMovies = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		lvMovies = (ListView) findViewById(R.id.lvMovies);
		lvMovies.setOnItemClickListener(this);

		loadMovies();
	}

	private void loadMovies() {
		final DataSource ds = DataSource.getInstance();
		if (ds.ensureLoaded(this)) {
			Log.d("MD", "loadMovies");
			lvMovies.setVisibility(View.VISIBLE);

			try {
				((MovieListAdapter) lvMovies.getAdapter()).getCursor().close();
			} catch (NullPointerException e) {
				// No adapter or cursor assigned
			}

			final Cursor moviesCursor = ds.getMatches(lvMovies.getTextFilter());
			startManagingCursor(moviesCursor);
			final MovieListAdapter mAdapter = new MovieListAdapter(this, moviesCursor);
			mAdapter.setFilterQueryProvider(this);
			lvMovies.setAdapter(mAdapter);

			reloadMovies = false;
		} else {
			showWrongDatabaseDialog();
		}
	}

	private void showWrongDatabaseDialog() {
		lvMovies.setVisibility(View.GONE);
		final String databasePath = MDPreferenceActivity.getDatabasePath(this);

		if (TextUtils.isEmpty(databasePath)) {
			Toast.makeText(this, R.string.database_not_selected_msg, Toast.LENGTH_LONG).show();
			showDatabaseChooser();
		} else {
			final AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setPositiveButton(getString(android.R.string.yes), this);
			builder.setNegativeButton(getString(android.R.string.no), this);

			builder.setMessage(getString(R.string.unable_to_open_database_msg, null == databasePath ? "empty" : databasePath));

			builder.setCancelable(false).create().show();
		}
	}

	public void onClick(DialogInterface dialog, int which) {
		if (which == DialogInterface.BUTTON_POSITIVE) {
			showDatabaseChooser();
		} else if (which == DialogInterface.BUTTON_NEGATIVE) {
			dialog.cancel();
			finish();
		}
	}

	private void setMoviesFilter(String filter) {
		if (!filter.equals(lvMovies.getTextFilter()))
			lvMovies.setFilterText(filter);
	}

	private void viewMovie(long code, int index) {
		final Intent next = new Intent(this, ViewMovieActivity.class);
		next.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		next.putExtra(ViewMovieActivity.MOVIE_CODE_EXTRA, code);
		next.putExtra(ViewMovieActivity.MOVIE_INDEX_EXTRA, index);
		startActivity(next);
		overridePendingTransition(R.anim.slide_up_in, R.anim.slide_up_out);
	}

	public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {
		switch (adapterView.getId()) {
			case R.id.lvMovies:
				viewMovie(id, index);
				break;
		}
	}

	public Cursor runQuery(CharSequence filter) {
		return DataSource.getInstance().getMatches(filter.toString());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		(new MenuInflater(this)).inflate(R.menu.menu_main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.menuMainDataBase:
				showDatabaseChooser();
				return true;
			case R.id.menuMainPreferences:
				showPreferences();
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private void showPreferences() {
		final Intent next = new Intent();
		next.setClass(this, MDPreferenceActivity.class);
		startActivity(next);
	}

	private void showDatabaseChooser() {
		final Intent next = new Intent(this, FileChooserActivity.class);
		next.putExtra(FileChooserActivity.FILE_FILTER_EXTRA, DATABASE_FILE_FILTER);
		startActivityForResult(next, Activity.RESULT_FIRST_USER);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && (!TextUtils.isEmpty(lvMovies.getTextFilter()))) {
			lvMovies.setFilterText("");
			return true;
		} else if (keyCode == KeyEvent.KEYCODE_SEARCH) {
			final Intent next = new Intent();
			next.setClass(this, AwesomePagerActivity.class);
			startActivity(next);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_FIRST_USER) {
			final String databasePath = data.getStringExtra(FileChooserActivity.FILE_PATH_EXTRA);
			MDPreferenceActivity.setDatabasePath(this, databasePath);
			Toast.makeText(this, getString(R.string.database_selected_msg, databasePath), Toast.LENGTH_LONG).show();
			DataSource.getInstance().close();
			reloadMovies = true;
		}
	}

	@Override
	protected void onStart() {
		super.onStart();

		if (reloadMovies)
			loadMovies();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);

		if (intent.hasExtra(FILTER_EXTRA)) {
			setMoviesFilter(intent.getStringExtra(FILTER_EXTRA));
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}
}